package jmine.tec.web.servlet.rest.subscription;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jmine.tec.subscription.Publisher;
import jmine.tec.subscription.PublisherManager;
import jmine.tec.utils.UnmodifiableTuple;
import jmine.tec.web.servlet.rest.RestImplementor;
import jmine.tec.web.servlet.rest.exception.HttpErrorException;
import bancosys.tec.persist.dao.BeanNotFoundException;

/**
 * @author takeshi
 */
public class RestPublisherImplementor extends RestImplementor {

    private PublisherManager publisherManager;

    /**
     * {@inheritDoc}
     */
    @Override
    public String getPreffix() {
        return "publisher";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object get(Map<String, String[]> parameters) throws BeanNotFoundException, HttpErrorException {
        final List<Publisher<?>> publishers = this.publisherManager.getPublishers();
        final List<String> list = new ArrayList<String>(publishers.size());
        for (Publisher<?> publisher : publishers) {
            list.add(publisher.identification());
        }
        return list;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object get(String identification, Map<String, String[]> parameters) throws BeanNotFoundException, HttpErrorException {
        final Publisher<?> publisher = this.publisherManager.getPublisher(identification);
        if (publisher == null) {
            throw new HttpErrorException(HttpServletResponse.SC_NOT_FOUND, identification);
        }
        return publisher;
    }

    /**
     * @return the publisherManager
     */
    public PublisherManager getPublisherManager() {
        return this.publisherManager;
    }

    /**
     * @param publisherManager the publisherManager to set
     */
    public void setPublisherManager(PublisherManager publisherManager) {
        this.publisherManager = publisherManager;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object prepareToSerialize(Object e, Map<String, String[]> map) throws HttpErrorException {
        Publisher<?> p = (Publisher<?>) e;
        return UnmodifiableTuple.newTuple(p.identification(), p.subscriptionSettingsParameters());
    }

}
